<?php
/**
 * Created by PhpStorm.
 * User: mengkang <i@mengkang.net>
 * Date: 2019/10/2 下午3:37
 */

include_once "./Url.php";

class Wget2
{

    /**
     * @var Url;
     */
    private $url;
    private $filename;
    private $debug = false;

    private $request;

    public function __construct($argv)
    {
        foreach ($argv as $index => $item) {
            if ($item == "mywget") {
                unset($argv[$index]);
            }

            if ($item == "-v") {
                $this->setDebug(true);
                unset($argv[$index]);
            }

            if ($item == "-O") {
                $this->filename = $argv[$index + 1];
                unset($argv[$index]);
                unset($argv[$index + 1]);
            }
        }

        $this->setUrl(array_pop($argv));


        if (!$this->filename) {
            $this->filename = pathinfo($this->url->getUri(), PATHINFO_BASENAME);
        }
    }

    private function setUrl($url)
    {
        $this->url = new Url($url);
    }

    private function setDebug($debug)
    {
        $this->debug = $debug;
    }

    private function createHttpRequest()
    {
        $this->request = sprintf("GET %s HTTP/1.1\r\nHost: %s:%s\r\nConnection: Close\r\n\r\n", $this->url->getUri(), $this->url->getHost(), $this->url->getPort());

        $this->log($this->request);
    }

    private function log($info)
    {
        if ($this->debug) {
            echo "\033[32m" . $info . "\033[0m\r\n";
        }
    }

    private function wget()
    {

        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket === false) {
            throw new RuntimeException("socket_create() failed: reason: " . socket_strerror(socket_last_error()));
        }

        $result = socket_connect($socket, $this->url->getIp(), $this->url->getPort());
        if ($result === false) {
            throw new RuntimeException ("socket_connect() failed: reason: ($result) " . socket_strerror(socket_last_error($socket)));
        }

        socket_write($socket, $this->request, strlen($this->request));

        $isHeader = true;
        while ($data = socket_read($socket, 2048)) {

            if ($data === false) {
                throw new RuntimeException ("socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)));
            }

            $this->log("read " . strlen($data) . " bytes");

            if (strlen($data) <= 0) {
                break;
            }

            if ($isHeader) {
                $data = substr($data, strpos($data, "\r\n\r\n") + 4);
                file_put_contents($this->filename, ""); // 清空下文件
                $isHeader = false;
            }

            file_put_contents($this->filename, $data, FILE_APPEND);
        }

        socket_close($socket);
        $this->log("Closing socket...");
    }

    public function run()
    {
        $this->createHttpRequest();
        $this->wget();
    }
}

$wget = new Wget2($argv);
$wget->run();